#pragma warning(disable:4996)
#include <iostream>
#include <winsock2.h>  //网络socket 套接字必须包含的一个一个头文件
#include <string>
#include <cstring>

#pragma comment(lib,"ws2_32.lib")
using namespace std;
uint16_t port = 8080;
string _ip = "101.43.250.247";
int main()
{
	WSADATA wsa;  //初始化网络环境
	if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) //采用的是x.x的网络
	{
		cout << "WSAStartup() fail " << endl;
		exit(-1);  //直接中止程序
	}
	else
	{
		cout << "WSAStartup() suceess " << endl;
	}
	
	//下面跟Linux系统下的操作一摸一样
	//开始套接字操作
	SOCKET _socket = socket(AF_INET, SOCK_DGRAM, 0); //套接字
	if (_socket == SOCKET_ERROR)
	{
		cout << "socek error" << endl;
		exit(-2);
	}
	struct sockaddr_in in;
	memset(&in, 0, sizeof(in));
	in.sin_family = AF_INET;
	in.sin_port = htons(port);
	in.sin_addr.S_un.S_addr = inet_addr(_ip.c_str()); 
	//同样无需进行绑定

	char buffer[1024];
	string message;
	while (true)
	{
		cout << "Enter##";
		fgets(buffer, sizeof(buffer), stdin);
		message = buffer;
		int sendf = sendto(_socket, message.c_str(), message.size()-1, 0, (struct sockaddr*)&in, sizeof(in));
		if (send < 0)
		{
			cout << "send error" << endl;
			exit(0);
		}
		char buff[1024];
		buff[0] = 0; //C风格的清空字符串
		struct sockaddr_in from;
		memset(&from, 0, sizeof(from));
		int len = sizeof(from);
		int recvf = recvfrom(_socket, buff, sizeof(buff) - 1, 0,(struct sockaddr*)&from,&len);
		if (recvf > 0)
		{
			buff[recvf] = 0;
			cout << "server 返回的消息是" << buff << endl;
		}
		else break;
	}
	WSACleanup();
	return 0;
}